package ai;

import handlers.NonAvatarMvtHandler;
import handlers.SkillHandler;

import java.util.ArrayList;

import map.Direction;
import map.Position;
import scheduler.DuplicateEventException;
import scheduler.Scheduler;
import skills.ActiveSkill;
import entity.Avatar;
import entity.Entity;

public class BattleAI extends AI {

	private Scheduler scheduler;
	private int speed;
	
	public BattleAI(Avatar avatar) {
		setAvatar(avatar);
		scheduler = Scheduler.getInstance();
		speed = 20;
	}

	@Override
	public boolean addEntity(Entity entity) {
		try {
			BattleBrain brain = new BattleBrain(entity);
			getEnemies().put(entity,brain);
			scheduler.schedule(brain, speed);
			return true;
		}
		catch(DuplicateEventException dee) {
			System.out.println(dee.toString());
			return false;
		}
	}

	@Override
	public void removeEntity(Entity entity) {
		scheduler.cancel(getEnemies().remove(entity));		
	}

	public void removeAll() {
		for(Entity e : getEnemies().keySet()) {
			removeEntity(e);
		}
	}
	
	private class BattleBrain extends Brain {
		int coolDown = 10;
		int reload = coolDown;
		Entity npc;
		
		public BattleBrain(Entity npc) {
			move = new NonAvatarMvtHandler(npc);
			duration = 6;
			this.npc = npc;
		}

		@Override
		public void execute() {		
			if(reload-- > 0) {
				if(maintain-- <= 0) {
					maintain = ranGen.nextInt(duration);
					dir = Direction.getRandomDir();
				}
				else {
					if(!move.move(dir)) {
						dir = Direction.getRandomDir();
						execute();
					}
				}	
			}
			else {
				reload = coolDown;
				shoot();
			}
		}
		
		public void shoot() {
			Position avatarPos = getAvatar().getPosition();
			SkillHandler skill = new SkillHandler(npc);
			ArrayList<ActiveSkill> as = npc.getOccupation().getActiveSkillList();
			
			Position p = npc.getPosition().substract(avatarPos);
			Direction dir = Direction.convert(p);
			int choice = ranGen.nextInt(as.size());
			npc.setDirection(dir);
			skill.useSkill(choice);
		}
	}
}
